import { xml2json } from '../utils/XmlUtils';
import timer from 'react-native-timer';
export const request = (url, body, overtime) => {
  return new Promise((respo) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: body,
    })
    .then((response) => response.json())
    .then((responseJson) => {
      respo(responseJson);
    })
    .catch((error) => {
      console.log('网络连接出错');
      reject(error);
    });
  });
};

export const requestXML = (url, body, overtime) => {
  return new Promise((resolve, reject)  => {
    let isReserve = false;
    fetch('http://www.dldhcwx.com/icmp-ums/dhc/sys/mobile.do', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: body,
    })
      .then((response) =>
        response.text())
      .then((responseText) => {
        if (isReserve) {
          return;
        }
        isReserve = true;
        try {
          let jsonStr = JSON.parse(JSON.stringify(xml2json(responseText)));
          resolve(jsonStr);
        }
        catch(err) {
          console.log(err);
        }
      })
      .catch((error) => {
        if (isReserve) {
          return;
        }
        reject(error);
      });
    timer.setTimeout(
      this, 'overtime', () => {
        if (!isReserve) {
          isReserve = true;
          reject({state: '-1'});
        }
      }, overtime
    );
  });
};

